<?php
//PingBuWang.Com
//Copyright (c) 2017~2099 http://www.pingbuwang.com All rights reserved.
namespace app\setting\controller;
use think\Cache;
use think\Request;
use think\Loader;
use mip\Htmlp;

use mip\AdminApiBase;
class ApiAdminTemplate extends AdminApiBase
{

    public function templateList()
    {
        // 从模板根目录下读取所有的模板文件夹
        $templateDir = opendir(PUBLIC_PATH . 'tpl');
        if ($templateDir) {
            while (false !== ($file = readdir($templateDir))) {
                if (substr($file, 0, 1) != '.' AND is_dir(PUBLIC_PATH . 'tpl' . DS . $file)) {
                    $dirs[] = $file;
                }
            }
            closedir($templateDir);
        }

        $templateArray = array();
        foreach ($dirs as $key => $val) {
            if (is_file(PUBLIC_PATH . 'tpl' . DS . $val . DS . 'template.json')) {
                $templateJson = file_get_contents(PUBLIC_PATH . 'tpl' . DS . $val . DS . 'template.json');

                $info1 = json_decode($templateJson);
                $pcThumb = $this->mipInfo['domain'] .'/tpl/'.$val.'/'.$info1->pc_thumbnail;
                $mobileThumb = $this->mipInfo['domain'] .'/tpl/'.$val.'/'.$info1->mobile_thumbnail;

                $templateArray[] = array('fileName' => $val, 'pcThumb'=>$pcThumb ,'mobileThumb'=> $mobileThumb ,'info' => $info1 );
            }
        }
 
        return jsonSuccess('',$templateArray);
    }

    /**
     * 选择生效的模板
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function set_selected() {
        if (Request::instance()->isPost()) {
            $fileName = input('post.fileName');

            $key = 'template';
            if(db("settings")->cache('c_setting_count',60*60,'setting')->where( "`key` = '" . $key . "'")->count() == 0){
                db("settings")->insert(array('key'=>$key,'val'=>$fileName));
            }else{
                db("settings")->where( "`key` = '" . $key . "'")->update(array('val' => $fileName));
            }
            Cache::clear('setting');
            return jsonSuccess('保存成功');
        }
    }

    /**
     * 根据模板路径名称获得模版的信息
     * @param $filename
     */
    public function get_info_by_filename(){
        $filename = input("post.fileName");

        // 如果没有传递该参数，则使用默认模板名称
        if(!$filename){
            $filename = config('mipInfo')['template'];
        }

        $res = model("app\setting\model\Template")->getInfoByFileName($filename);
        if($res){
            return jsonSuccess("获得模板信息",$res);
        }

        return jsonError("未能获得模板：".$filename);
    }

    /**
     * 获取文件的树形结构
     */
    public function get_for_itree(){
        $filename = input("post.fileName");

        $rootPath = realpath(PUBLIC_PATH . 'tpl' . DS . $filename . DS ).DS;

        // 判断模板文件夹是否存在
        if (!is_dir($rootPath )) {
            return  jsonError('模板文件夹 '.$filename.' 不存在');
        }
        if (!is_file($rootPath . 'template.json')) {
            return  jsonError('模板文件夹 '.$filename.' 下的template.json文件不存在');
        }

        // 读取模板文件json信息
        $templateJson = file_get_contents(PUBLIC_PATH . 'tpl' . DS . $filename . DS . 'template.json');
        $info1 = json_decode($templateJson);
        $tplName = $info1->title;


        // 读取文件夹及其下的所有文件，并组成itree的数据JSON

        $fileIcon = ['site'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/site_32px.png',
            'folder'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/folder_32px.png',
            'js'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/js.png',
            'css'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/css.png',
            'jpg'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/jpg.png',
            'png'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/png.png',
            'gif'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/gif_32px.png',
            'svg'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/svg_32px.png',
            'html'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/html_32px.png',
            'json'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/json_32px.png',
            'otherfile'=>$this->mipInfo['domain'].'/assets/common/images/fileicon1/file_32px.png',
            ];

        $arr = [];
        fetch_file_itree($arr, $rootPath ,$rootPath ,$fileIcon );

        foreach ($arr as $k3=>$v3){
            $v3['expand'] = true;
            $arr[$k3] = $v3;
        }

        $arr2 = [ ['title'=>$filename,'type'=>'folder','editable'=>false , 'tplname'=>$tplName,'expand'=>true,'icon'=>$fileIcon['site'], 'children'=>$arr ] ];

        return jsonSuccess('获取模板文件夹成功',$arr2);

    }

    public function get_srcfile_content(){
        $fullpath = input("post.fullpath");

        $txt = read_file_text($fullpath);

        return jsonSuccess('获取文件内容成功',$txt);

    }

    public function create_subfolder(){
        $basepath = input("post.basepath");
        $subfolder_filename = input('post.subfolder_filename');

        // 验证basepath是否存在
        $res = create_folder($basepath,$subfolder_filename);
        if($res === 0 ){
            return jsonSuccess('文件夹创建成功');
        }else if($res === 2){
            return jsonError('基础路径不存在，无法创建子路径');
        }else if($res == 3 ){
            return jsonError('文件夹'.$subfolder_filename.'已经存在，不能重复创建');
        }
        return jsonError('由于未知原因创建路径'.$subfolder_filename.'失败，请联系管理员或稍后再试！');

    }

    public function remove_file(){
        $filepath = input("post.filepath");

        remove_file($filepath);
        return jsonSuccess('文件删除成功');
    }



}